package com.example.test_mqtt

import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity : AppCompatActivity() {
    private lateinit var mqttManager: MQTTManager
    private lateinit var editText: EditText
    private lateinit var textView: TextView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        editText = findViewById(R.id.et)
        textView = findViewById(R.id.tv)

        // 初始化 MQTT 管理器
        mqttManager = MQTTManager(
            context = this,
            serverUri = "tcp://10.161.9.80:1883", // 公共测试服务器
            clientId = "android_client_${System.currentTimeMillis()}"
        )

        // 连接 MQTT 服务器
        mqttManager.connect()


        //订阅livedata更新ui
        mqttManager.incomingMessage.observe(this){
            textView.text = it.payload.decodeToString()
        }


    }

    fun send(view: View) {
        mqttManager.publish(
            topic = "test/topic",
            message = editText.text.toString()
        )
    }
    override fun onDestroy() {
        super.onDestroy()
        mqttManager.disconnect() // 避免内存泄漏
    }
}